<?php
$this->headLink(array('href' => '/cms/styles/style.css', 'rel' => "stylesheet", 'type' => "text/css"));
$this->headLink(array('href' => '/cms/styles/data-table.css', 'rel' => "stylesheet", 'type' => "text/css"));



$this->headScript()
	->appendFile('/cms/scripts/dojo/dojo.js','',array('djConfig'=> 'parseOnLoad:true, isDebug:false'))
	->setAllowArbitraryAttributes(true);


$this->headLink(array('href' => '/cms/scripts/shadowbox-3.0rc1/shadowbox.css', 'rel' => "stylesheet", 'type' => "text/css"));
$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/shadowbox-3.0rc1/shadowbox.js');

$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/content.js');
//$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/Popup.js');
$this->headScript(Zend_View_Helper_HeadScript::FILE,'/cms/scripts/TableData.js');
$this->headScript(Zend_View_Helper_HeadScript::SCRIPT,"
	//var newsId = {$this->news_id};
	//filter_setup = ['from_date','".date('Y-m-d',mktime(0,0,0,date('m'),date('d')-10,date('Y')))."','to_date','".date('Y-m-d')."'];");

$this->headScript(Zend_View_Helper_HeadScript::SCRIPT,<<<EOD

//dojo.require("dijit.form.DateTextBox");
dojo.require("dijit.InlineEditBox");
dojo.require("dojo.parser");

var shadowbox_callback = function () {};

reset_shadowbox_callback = function () {
	shadowbox_callback = function () {};
}

Shadowbox.init({
    players:    ['html', 'iframe', 'img', 'swf'],
    onClose: function() { shadowbox_callback() }
});


window.onload = function () {

	ordersTable = new tableData('mainOrdersTable');

    //столбик с датой заказа
	ordersTable.registerWidget('order_date',
		function (params) {
			var divEl = document.createElement('DIV');
			divEl.innerHTML = params['value'];
			divEl.setAttribute('dojoType','dijit.form.DateTextBox(');
			return divEl;
		});

    //столбик с именем пользователя
	ordersTable.registerWidget('users_login',
		function (params) {
			var divEl = document.createElement('DIV');
			var aEl = document.createElement('A');
			aEl.href ='javascript:;';
			aEl.innerHTML = params['value'];
			aEl.onclick = function () {
                Shadowbox.open({
			      player:     'iframe',
			      title:      'Информация о пользователе',
			      content:    '/cms/users/edit/user_id/'+params['user_id'],
			      height:     450,
			      width:      750
			  });
			}
			divEl.appendChild(aEl);
			divEl.setAttribute('dojoType','dijit.form.DateTextBox(');
			return divEl;
		});

    //столбик с именем пользователя
	ordersTable.registerWidget('order_summa',
		function (params) {
			var divEl = document.createElement('DIV');
			divEl.innerHTML = params['value'];
			divEl.setAttribute('dojoType','dijit.form.DateTextBox(');
			return divEl;
		});

	//столбик с редактирование
	ordersTable.registerWidget('order_edit',
		function (params) {
  		    var divEl = document.createElement('DIV');
			divEl.className = 'icon';
			var imgEl = document.createElement('IMG');
			imgEl.src = '/cms/images/document_list.png';
			var aEl = document.createElement('A');
			aEl.href = 'javascript:;';
			aEl.onclick = function () {
				shadowbox_callback = function () {
			   		gotoPage(1);
			   		reset_shadowbox_callback();
			   	}

                Shadowbox.open({
			      player:     'iframe',
			      title:      'Просмотр заказа',
			      content:    '/cms/orders/edit/order_id/'+params['id'],
			      height:     450,
			      width:      750
			  });
			}
			divEl.appendChild(aEl);
			aEl.appendChild(imgEl);

			return divEl;
		});

    //флажок статуса заказа
	ordersTable.registerWidget('orders_status',
        function (params){
            var divEl = document.createElement('DIV');
            divEl.innerHTML = '<select onchange=""></select>';

            var sel = divEl.lastChild;
            var id = params['id'];
            sel.id = "status_" + id;
            sel.onchange = function(){
                var val = document.getElementById("status_" + id).value;
//                val = val + ' - ' + params['id'];
//                alert(val);
                //отсылаем запрос
                dojo.xhrGet({
                    url: "/cms/orders/flag/id/"+params['id']+"/flag/" + val,
					load: function(response, ioArgs) {
//                        imgEl.src = '/cms/images/' + (parseInt(response) == 1 ? 'eye.png' : 'eye_disabled.png');
						return response;
					},
					error: function(response, ioArgs){
                        alert("An error occurred, with response: " + response);
                        return response;
					},
                    handleAs: "text",
                    sync: true
                });
            }

            for (var i in params['flagNames']){
                var option = document.createElement("option");
                option.value = i;
                option.selected = false;

                if( params['value'] == i ) option.selected = true;

//            if(classify.units[i].selected) option.selected = false;

                var text = document.createTextNode(params['flagNames'][i]);
                option.appendChild(text);
                sel.appendChild(option);
            }

/*            var option = document.createElement("option");

            option.value = 'is_vip';

            text = document.createTextNode('test2');
            option.appendChild(text);
            sel.appendChild(option);

            divEl.appendChild(sel);*/

            return divEl;
        }
        );

    ordersTable.registerWidget('post_print',
    	function (params) {
    		var divEl = dojo.create('div',{style : 'text-align: center'});
    		var aEl = dojo.create('a',{href:'/cms/orders/postprint/id/'+params['id']},divEl);
    		dojo.create('img',{src:'/cms/images/printer.png'},aEl);
    		return divEl;
    	});




    callData([]); //загружаем данные


    // Вешаем событие на кнопку, чтобы при нажатии открывалось окошко для заполнения новго заказа
    dojo.query('#newOrderBtn').connect('onclick',

    	function () {
		   	shadowbox_callback = function () {
		   		gotoPage(1);
		   		reset_shadowbox_callback();
		   	}

    		Shadowbox.open({
			      player:     'iframe',
			      title:      'Новый заказ',
			      content:    '/cms/orders/add',
			      height:     450,
			      width:      750
			  });
    	});

    //экспорт в эксель
    dojo.query('#exportBtn').connect('onclick',
    	function () {
    	   var message = "Срок выбираемых данных должен быть не более 3-х месяцев";
           
    		if(undefined==exportBtnParams[3]||undefined==exportBtnParams[5]){
    		  alert("Введите дату");
              return;
    		}
            
                      
            var startDate = new Date();var tmp = exportBtnParams[3].split('-');
            startDate.setFullYear(tmp[0],tmp[1],tmp[2]);
           
            var endDate = new Date();var tmp = exportBtnParams[5].split('-');
            endDate.setFullYear(tmp[0],tmp[1],tmp[2]);
             
            if((endDate.getTime()-startDate.getTime())/1000>7776000){
                alert(message);
                return;
            }
            
    		window.location.href="/cms/orders/export/"+
    			exportBtnParams.join('/');
            
            
    		
    	});

} //onload



//загрузка заказов
var callData = function (params) {
	dojo.xhrGet({
	    url: "/cms/orders/widget/limit_from/"+limit_setup[0]+"/limit_amount/"+limit_setup[1]+'/'+params.join('/'),
	    load: function(responseObject, ioArgs){
	      var pagesPlace = document.getElementById('pagesPlace');
	      pagesPlace.innerHTML = '';
	      exportBtnParams = params;

	      //разбираемся со страницами
	      var total_pages = Math.ceil(responseObject['total_length']/rows_per_page);

	      var appendPageAction = function (page) {
	        var aEl = document.createElement('A');
	      	aEl.innerHTML = i;
	      	aEl.href = 'javascript:;';
	      	aEl.onclick = function () { gotoPage(page) }
	      	return aEl;
	      }

	      var appendDelimetr = function () {
	        var delimetr = document.createElement('SPAN');
	      	delimetr.innerHTML = '&nbsp;';
	      	return delimetr;
	      }


	      if (current_page>1) {
	      	var aEl = document.createElement('A');
	      	aEl.innerHTML = '&lt; Предыдущая';
	      	aEl.href = 'javascript:;';
	      	aEl.onclick = function () { gotoPage(current_page-1) }
	      	pagesPlace.appendChild(aEl);
	      	pagesPlace.appendChild(appendDelimetr());
	      }

	      var start_from = current_page-3;
	      if (start_from>1) {
	      	var dots = document.createElement('SPAN');
	      	dots.innerHTML = '...&nbsp;';
	      	pagesPlace.appendChild(dots);
	      } else {
	      	start_from = 1;
	      }
	      for (var i=start_from;i<current_page;i++) {
	      	pagesPlace.appendChild(appendPageAction(i));

	      	pagesPlace.appendChild(appendDelimetr());
	      }

	      var cur_pg = document.createElement('SPAN');
	      cur_pg.innerHTML = current_page;
	      pagesPlace.appendChild(cur_pg)

	      pagesPlace.appendChild(appendDelimetr());


	      var end_to = current_page+3;
	      if (end_to>total_pages) end_to = total_pages;

	      for (var i=current_page+1;i<=end_to;i++) {
	      	pagesPlace.appendChild(appendPageAction(i));

	      	pagesPlace.appendChild(appendDelimetr());
	      }

	      if (end_to<total_pages) {
	        var dots = document.createElement('SPAN');
	      	dots.innerHTML = '...&nbsp;';
	      	pagesPlace.appendChild(dots);
	      }

	      if (current_page<total_pages) {
	      	var aEl = document.createElement('A');
	      	aEl.innerHTML = 'Следующая &gt;';
	      	aEl.href = 'javascript:;';
	      	aEl.onclick = function () { gotoPage(current_page+1) }
	      	pagesPlace.appendChild(aEl);
	      	pagesPlace.appendChild(appendDelimetr());
	      }

            ordersTable.draw(responseObject['data']);

		  //dojo.parser.parse(document.getElementById('mainNewsTable'));

	      return responseObject;
	    },
	    error: function(response, ioArgs){
	      alert("An error occurred, with response: " + response);
	      return response;
	    },
	    handleAs: "json",
	    sync: true
	  });
}

//exportBtn params
var exportBtnParams = [];

var current_page = 1;
var rows_per_page = 10;
var limit_setup = [0,rows_per_page];

var filter_setup = new Array();
var MakeFilter = function () {
	filter_setup = ['f_status', document.getElementById('f_status').value];
	if( document.getElementById('f_login').value != "" )
	   filter_setup.push('f_login', document.getElementById('f_login').value);

	if( document.getElementById('f_from').value != "" )
	   filter_setup.push('f_from', document.getElementById('f_from').value);

	if( document.getElementById('f_to').value != "" )
	   filter_setup.push('f_to', document.getElementById('f_to').value);

//	if (document.getElementById('publish_f').checked) {
//		filter_setup.push('publish_f','1');
//	}

	gotoPage(1);
}

var gotoPage = function (page) {
	current_page = page;
	limit_setup = [(page-1)*rows_per_page,rows_per_page];
	callData(filter_setup);
}

EOD
);

$this->layout()->body_attr = 'class="modal"';
?>

<form method="POST" action="" id="filterform">
<p class = "stnd_font">
С: <input type="text" id="f_from" value="<?=$this->f_from?>" class="modalInput"> По: <input type="text" id="f_to" value="<?=$this->f_to?>" class="modalInput">
<br />
Статус:
        <select name="f_status" id='f_status' class="modalInput">
            <option name="f_status" id='f_status' value = "0">Все</option>
            <?php foreach($this->flagNames as $index => $f) { ?>
                <option id='f_status' name="f_status" value="<?=$index?>"><?=$f?></option>
            <?php } ?>
        </select>
Пользователь: <input type="text" name="f_login" id="f_login" value="<?=$this->f_login?>" class="modalInput">
<input type="button" style="width:130px" value="Фильтровать" class="okButton" onclick="MakeFilter()" />
</p>
</form>
</table>

<div style="float:right; margin-top: -8px; margin-bottom: 4px;">
  <button type="button" class="okButton" id="exportBtn"><img src="/cms/images/table.gif" /> Экспортировать</button>
  <button type="button" class="okButton" id="newOrderBtn"><img src="/cms/images/plus.png" /> Добавить заказ</button>
</div>
<p class="stnd_font">Страницы: <span id="pagesPlace">&nbsp;</span></p>
<table width="100%" cellspacing="0" class="table-data">
<thead>
  <tr>
    <th width="160" nowrap="nowrap" scope="col">Дата</th>
    <th nowrap="nowrap" scope="col">Покупатель</th>
    <th>Статус</th>
    <th nowrap="nowrap" scope="col">Сумма</th>
    <th>Детали</th>
    <th>Бланки</th>
  </tr>
</thead>
<tbody id="mainOrdersTable"></tbody>
</table>
